public class Tree {

    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    private TreeNode root;

    //插入
    public void insert(int val) {
        TreeNode node = new TreeNode(val);
        if(root == null) {
            root = node;
            return;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null) {
            prev = cur;
            if(cur.val == val) {
                return;
            } else if(cur.val > val) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }
        if(prev.val > val) {
            prev.left = node;
        } else {
            prev.right = node;
        }
    }

    //查找
    public TreeNode find(int val) {
        TreeNode cur = root;
        while(cur != null) {
            if(cur.val == val) {
                return cur;
            } else if(cur.val > val) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }
        return null;
    }

    //删除
    public void delete(int val) {
        if(root == null) {
            return;
        }
        TreeNode parent = null;
        TreeNode cur = root;
        while(cur != null) {
            parent = cur;
            if(cur.val == val) {
                break;
            } else if(cur.val > val) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }

        if(cur.left == null) {
            if(cur == root) {
                root = cur.right;
            } else if(parent.left == cur) {
                parent.left = cur.right;
            } else {
                parent.right = cur.right;
            }
        } else if(cur.right == null) {
            if(cur == root) {
                root = cur.left;
            } else if(parent.left == cur) {
                parent.left = cur.left;
            } else {
                parent.right = cur.left;
            }
        } else {
            //左右子树均不为空
            //寻找左子树最右边的结点作为新的根结点、
            TreeNode tmp = cur.left;
            TreeNode prev = null;
            while(tmp.right != null) {
                prev = tmp;
                tmp = tmp.right;
            }
            cur.val = tmp.val;
            prev.right = tmp.left;
        }
    }
}
